package fileutils

import (
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
	"strings"
)

type FindFileService struct {
	dir           string
	excludeSuffix string
	includeSuffix string
}

func NewFindFileService() *FindFileService {
	return &FindFileService{
		dir:           FindRootDir(),
		excludeSuffix: ".docx,.exe",
	}
}
func (self *FindFileService) Dir() string {
	return self.dir
}

func (self *FindFileService) SetDir(dir string) {
	self.dir = dir
}

func (self *FindFileService) IncludeSuffix() string {
	return self.includeSuffix
}

func (self *FindFileService) SetIncludeSuffix(includeSuffix string) {
	self.includeSuffix = includeSuffix
}

func (self *FindFileService) ExcludeSuffix() string {
	return self.excludeSuffix
}

func (self *FindFileService) SetExcludeSuffix(excludeSuffix string) {
	self.excludeSuffix = excludeSuffix
}

func (self *FindFileService) FindFiles() ([]string, error) {
	//var dirPath = fileutils.FindRootDirGoMod() + consts.Webcmd
	var notIncludes = strings.Split(self.excludeSuffix, ",")
	var includes = strings.Split(self.includeSuffix, ",")
	var files = make([]string, 0)
	// 指定需要遍历的目录
	// 使用filepath.Walk遍历目录
	err := filepath.Walk(self.dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			logrus.Error(err)
			return err
		}
		// 如果是文件，可以进行额外操作，比如读取文件内容
		if !info.IsDir() {
			for _, filter := range notIncludes {
				if strings.HasSuffix(path, filter) {
					return nil
				}
			}
			for _, match := range includes {
				if !strings.HasSuffix(path, match) {
					return nil
				}
			}
			files = append(files, path)

		}
		// 返回nil继续遍历
		return nil
	})

	if err != nil {
		logrus.Error("Error walking the path:", err)
	}
	return files, err
}
